﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.BLL.Order;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Entity.Order;
using SHKF.B2C.YouZanYun.BLL;
using SHKF.B2C.YouZanYun.Model.Dto.Order;
using SHKF.B2C.YouZanYun.Model.Dto.Order.Msg;
using SHKF.B2C.YouZanYun.Model.Dto.Order.Msg.info;
using SHKF.B2C.YouZanYun.Model.Dto.Secret;
using SHKF.B2C.YouZanYun.Model.Dto.Token;
using SHKF.B2C.YouZanYun.Model.Entity.Order;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SHKF.B2C.YouZanYun.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class OrderController : Base2Controller
    {
        private readonly ShopMapBLL shopMapBLL;
        private readonly YZYOrderBLL yzyOrderBLL;
        private readonly OrderBLL orderBll;
     

        public OrderController(
             ShopMapBLL shopMapBLL,
           YZYOrderBLL yzyOrderBLL,
           OrderBLL orderBll,
           IServiceProvider serviceProvider,
           ILogger<OrderController> logger) : base(serviceProvider, logger)
        {
            this.shopMapBLL = shopMapBLL;
            this.yzyOrderBLL = yzyOrderBLL;
            this.orderBll = orderBll;
        }

        public async Task<IActionResult> Post()
        {
            IHeaderDictionary headers = base.HttpContext.Request.Headers;
            string strEventType = ""; //消息的业务标识，用于区分消息事件类型。英文表示的消息，具体详见各个消息事件的业务标识
            string strEventSign = ""; //防伪签名 ：MD5 (client_id+entity+client_secret); 其中 entity 是从 RequestBody 读取的内容

            if (headers.ContainsKey("Event-Type"))
            {
                strEventType = headers["Event-Type"];

                this.logger.LogInformation("Event-Type:" + strEventType);
            }

            if (headers.ContainsKey("Event-Sign"))
            {
                strEventSign = headers["Event-Sign"];

                this.logger.LogInformation("Event-Sign:" + strEventSign);
            }

            var request = this.Request;
            string json = "";
            if (request.Method.ToLower().Equals("post"))
            {
                request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(request.Body, Encoding.UTF8);
                json = reader.ReadToEnd();
                request.Body.Seek(0, SeekOrigin.Begin);
            }


            SuccessDto success = new SuccessDto();
            switch (strEventType)
            {
                //case "trade_TradeCreate":  
                //case "trade_TradePaid": //交易支付 
                case "trade_TradeBuyerPay": //买家付款(即商家待发货)
                    await this.trade_TradeBuyerPay(json);

                    //更新有赞云

                    break;
                default:
                    this.logger.LogInformation("null Event-Type");
                    break;
            }

            return new JsonResult(success);
        }

        private async Task<string> trade_TradeBuyerPay(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                this.logger.LogInformation("json:" + json);

                OrderDto order = JsonConvert.DeserializeObject<OrderDto>(json);
                string msg = HttpUtility.UrlDecode(order.msg, Encoding.UTF8);
                OrderMsg orderMsg = JsonConvert.DeserializeObject<OrderMsg>(msg);

                //获取Token 
                string authority_id = order.kdt_id.ToString();
                TokenYZYDto token = await base.GetToken(authority_id);
                if (token != null)
                {
                    if (!string.IsNullOrEmpty(token.message))
                    {
                        base.WriteInformation("CallBack", $"authority_id:{this.httpClient.authority_id }:{token.message} code:{token.code}");
                        return token.message;
                    }

                    //解密收货人信息
                    List<string> sources = new List<string>();
                    Address_Info address_info = orderMsg.full_order_info.address_info;

                    string receiver_tel = address_info.receiver_tel;
                    string delivery_address = address_info.delivery_address;
                    string receiver_name = address_info.receiver_name;
                    string buyer_phone = orderMsg.full_order_info.buyer_info.buyer_phone;

                    sources.Add(receiver_tel);
                    sources.Add(delivery_address);
                    sources.Add(receiver_name);
                    sources.Add(buyer_phone);

                    DecryptsDto decrypts = await this.httpClient.DecryptBatch(sources);
                    if (decrypts.code != 200)
                    {
                        base.WriteInformation("CallBack->DecryptBatch", $"code:{decrypts.code} message:{decrypts.message}");
                    }
                    else
                    {
                        receiver_tel = decrypts.data[address_info.receiver_tel].ToString();
                        delivery_address = decrypts.data[address_info.delivery_address].ToString();
                        receiver_name = decrypts.data[address_info.receiver_name].ToString();
                        buyer_phone = decrypts.data[orderMsg.full_order_info.buyer_info.buyer_phone].ToString();
                    }

                    address_info.receiver_tel = receiver_tel;
                    address_info.delivery_address = delivery_address;
                    address_info.receiver_name = receiver_name;

                    TradeContentEntity orderContent = new TradeContentEntity();
                    orderContent.buyer_phone = buyer_phone;

                    //主体信息  
                    CreateOrder(orderContent, order, orderMsg.full_order_info);

                    //订单收货地址信息结构
                    CreateOrderDelivery(orderContent, address_info);

                    //订单买家信息结构体
                    CreateOrderBuyer(orderContent, orderMsg.full_order_info.buyer_info);

                    //支付信息
                    CreateOrderPlay(orderContent, orderMsg.full_order_info.pay_info);

                    CreateOrderPromotion(orderContent, orderMsg.order_promotion);

                    //备注
                    CreateOrderRemark(orderContent, orderMsg.full_order_info.remark_info);

                    //优惠暂时没有

                    //明细
                    List<TradeDetailEntity> orderDetails = new List<TradeDetailEntity>();
                    List<Orders> details = orderMsg.full_order_info.orders;
                    if (details != null)
                    {
                        foreach (Orders detail in orderMsg.full_order_info.orders)
                        {
                            orderDetails.Add(detail);
                        }
                    }

                    //保存有赞云的数据
                    int result = this.yzyOrderBLL.SaveAll(orderContent, orderDetails);
                    if (result >= 0)
                    {
                        if (result != 2)
                        {
                            base.WriteInformation("trade_TradeBuyerPay", $"1.保存有赞云单据{orderContent.id}成功!");
                        }

                        //保存解析后到PtE_LM 
                    } 

                }
                else
                {
                    base.WriteInformation("trade_TradeBuyerPay", order.kdt_id + "token为空");
                }
            }

            return "";
        }

        private void CreateOrder(TradeContentEntity orderContent, OrderDto order, Full_Order_Info full_order_info)
        {
            orderContent.id = order.id;
            orderContent.kdt_id = order.kdt_id;
            orderContent.kdt_name = order.kdt_name;
            orderContent.msg_id = order.msg_id;
            orderContent.root_kdt_id = order.root_kdt_id;
            orderContent.sendCount = order.sendCount;
            orderContent.status = order.status;

            orderContent.created = full_order_info.order_info.created; ;
            orderContent.update_time = full_order_info.order_info.update_time;
            orderContent.pay_time = full_order_info.order_info.pay_time;
            orderContent.pay_type = full_order_info.order_info.pay_type;
            orderContent.refund_state = full_order_info.order_info.refund_state;
        }

        private void CreateOrderDelivery(TradeContentEntity orderContent, Address_Info address_info)
        {
            //经纬度
            address_extra address_Extra = JsonConvert.DeserializeObject<address_extra>(address_info.address_extra);

            orderContent.longitude = address_Extra.lon;
            orderContent.latitude = address_Extra.lat;
            orderContent.areaCode = address_Extra.areaCode;
            orderContent.delivery_address = address_info.delivery_address;
            orderContent.delivery_city = address_info.delivery_city;
            orderContent.delivery_district = address_info.delivery_district;
            orderContent.delivery_end_time = address_info.delivery_end_time;
            orderContent.delivery_postal_code = address_info.delivery_postal_code;
            orderContent.delivery_province = address_info.delivery_province;
            orderContent.delivery_start_time = address_info.delivery_start_time;
            orderContent.receiver_name = address_info.receiver_name;
            orderContent.receiver_tel = address_info.receiver_tel;
        }

        private void CreateOrderBuyer(TradeContentEntity orderContent, Buyer_Info buyer_info)
        {
            orderContent.yz_open_id = buyer_info.yz_open_id;
            orderContent.outer_user_id = buyer_info.outer_user_id;
        }

        private void CreateOrderPlay(TradeContentEntity orderContent, Pay_Info pay)
        {
            orderContent.total_fee = pay.total_fee;
            orderContent.payment = pay.payment;
            orderContent.post_fee = pay.post_fee;
        }

        private void CreateOrderPromotion(TradeContentEntity orderContent, Order_Promotion promotion)
        {
            if (promotion != null)
            {
                orderContent.discount_fee = promotion.item_discount_fee + promotion.order_discount_fee;
            }

        }

        private void CreateOrderRemark(TradeContentEntity orderContent, Remark_Info remark)
        {
            orderContent.buyer_message = remark.buyer_message;
            orderContent.star = remark.star;
            orderContent.trade_memo = remark.trade_memo;
        }

        private OrderContentEntity CreateOrder(TradeContentEntity orderContent, OrderMsg orderMsg)
        {
            OrderContentEntity orderEntity = new OrderContentEntity();

            int shopSN = 0;
            ShopMapEntity shopMap = this.shopMapBLL.GetShop(orderContent.kdt_id, PlatformEnum.Mtsg);
            if (shopMap != null)
            {
                shopSN = shopMap.ShopSN;
            }
            orderEntity.ShopSN = shopSN;
            orderEntity.app_poi_code = orderContent.kdt_id;
            orderEntity.ID = orderContent.id;
            orderEntity.status = int.Parse(orderContent.status );
            //orderEntity.order_id = long.Parse( order.order_id );
            //orderEntity.wm_order_id_view = order.id;
            orderEntity.wm_poi_name = orderContent.kdt_name;
            //orderEntity.wm_poi_address = HttpUtility.UrlDecode(order.wm_poi_address);
            //orderEntity.wm_poi_phone = order.wm_poi_phone;
            orderEntity.recipient_address = orderContent.delivery_address;
            orderEntity.recipient_phone = orderContent.receiver_tel;
            orderEntity.recipient_name = orderContent.receiver_name; 
            orderEntity.total = orderContent.payment;
            orderEntity.total_fee = orderContent.total_fee;
            orderEntity.caution = orderContent.buyer_message;
            //orderEntity.shipper_phone = order.shipper_phone;
            //orderEntity.shipper_phone = order.shipper_phone;
            int has_invoiced = 0;
            if(orderMsg.full_order_info != null && orderMsg.full_order_info.invoice_info != null )
            {
                if( orderMsg.full_order_info.invoice_info.user_name != "")
                {
                    has_invoiced = 1;
                }
                orderEntity.has_invoiced = has_invoiced;
                orderEntity.invoice_title = orderMsg.full_order_info.invoice_info.user_name;
            }
             
            orderEntity.Platform = PlatformEnum.YouZanYun;
            orderEntity.ctime = orderContent.created;
            orderEntity.utime = orderContent.update_time;
             
            //if (order.delivery_time == 0)
            //{
            //    orderEntity.delivery_time = new DateTime(1900, 1, 1);
            //}
            //else
            //{
            //    orderEntity.delivery_time = DateTimeUtil.TimeStampToDateTime(order.delivery_time);
            //}

            // orderEntity.day_seq = order.day_seq;

            //orderEntity.total_weight = order.total_weight;
            return orderEntity;
        }

        private List<OrderDetailEntity> CreateOrderDetail(List<TradeDetailEntity> orderDetails)
        {
           
            List<OrderDetailEntity> list = new List<OrderDetailEntity>();
            foreach (TradeDetailEntity orderDetailPush in orderDetails)
            {
                OrderDetailEntity orderDetailEntity = new OrderDetailEntity();

                orderDetailEntity.FKSN = 0;
                orderDetailEntity.actual_price = orderDetailPush.total_fee;
                orderDetailEntity.original_price = orderDetailPush.price;
                orderDetailEntity.app_medicine_code = orderDetailPush.item_id.ToString();
                orderDetailEntity.product_name = orderDetailPush.title;
                orderDetailEntity.upc = orderDetailPush.item_barcode;
                orderDetailEntity.qty = orderDetailPush.num;
                orderDetailEntity.price = orderDetailPush.price;
                orderDetailEntity.box_num = 0;
                orderDetailEntity.box_price = 0;
                // orderDetailEntity.unit = orderDetailPush.unit;
                //orderDetailEntity.food_discount = orderDetailPush.food_discount;
                //orderDetailEntity.weight = orderDetailPush.weight;
                // orderDetailEntity.weight_unit = orderDetailPush.weight_unit;

                //orderDetailEntity.ProductSN = this.medicineBLL.GetProductSN(orderDetailPush.upc, app_poi_code); 
                //this.logger.LogInformation($"ProductSN :{orderDetailEntity.ProductSN} app_medicine_code:{orderDetailPush.app_medicine_code}  app_poi_code:{app_poi_code}");

                list.Add(orderDetailEntity);
            }
            return list;
        }

    }
}
